var searchResults = JSON.parse(Ti.App.Properties.getString("ug_search"));

var distanceConversion = {
	'10': 0.15,
	'25': 0.36,
	'50': 0.73,
	'100': 1.45,
	'250': 3.62,
	'500': 7.23,
	'1000': 29
};
var mapview = null;

Ti.Geolocation.getCurrentPosition(function(e) {
	Ti.API.info('GetCurrentPosition: ' + JSON.stringify(e));
	if (e.error) {
		Ti.API.info('error ' + JSON.stringify(e.error));
		return;
	}

	searchResults.currentLocation.lng  = e.coords.longitude;
	searchResults.currentLocation.lat = e.coords.latitude;
});

var annotations = [];
for (var i = 0; i< searchResults.usergroups.length; i++ ) {
	var usergroup = searchResults.usergroups[i];
	
	annotations.push(
		Ti.Map.createAnnotation({
		    latitude:usergroup.Latitude,
		    longitude:usergroup.Longitude,
		    title:usergroup.Name,
		    subtitle:usergroup.City + ', ' + usergroup.Region,
		    pincolor:Ti.Map.ANNOTATION_RED,
		    animate:true,
		    leftButton: '../images/appcelerator_small.png',
		    myid:1 // CUSTOM ATTRIBUTE THAT IS PASSED INTO EVENT OBJECTS
		})
	);
}


var delta = distanceConversion[searchResults.distance];

var currentLocation = {
		latitude:searchResults.currentLocation.lat, 
		longitude:searchResults.currentLocation.lng, 
        latitudeDelta:delta, 
        longitudeDelta:delta
    };
 
createMapView();

win.addEventListener('close', function(e) {
	if (DotNetNuke.isAndroid()) {
		removeMapView();
	}
});

Ti.App.addEventListener('show_results_map', function() {
	createMapView();
});

function createMapView() {
	var mapview = Ti.Map.createView({
	    mapType: Ti.Map.STANDARD_TYPE,
	    location: currentLocation,
	    region: currentLocation,    
	    animate:true,
	    regionFit:true,
	    userLocation:true,
	    annotations:annotations
	});
	mapPanel.add(mapview);
}

function removeMapView() {
	
	if (mapview == null) {
		return;
	}
	mapPanel.remove(mapview);
	mapview.onDestroy();
	mapview = null;
}
